package com.ruoyi.web.service;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.IsoFields;
import java.util.*;

@Service
public class C2OntimeRateService {
    @Autowired
    private DruidDataSource druidDataSource;

    public Map<String, Object> getC2ReleaseSucRateByMonths() {
        // 返回数据的结构
        Map<String, List<String>> timePeriods = new HashMap<>();
        List<String> months = new ArrayList<>();
        List<Integer> totalCounts = new ArrayList<>();
        List<Integer> releaseStatusCounts = new ArrayList<>();
        List<Double> percentages = new ArrayList<>();

        String sql = "SELECT `buildTime`, COALESCE(`releaseStatus`, 0) AS `releaseStatus` FROM `c2_version_info`;";
        System.out.println("Executing SQL: " + sql);

        // 使用 TreeMap 确保按时间顺序存储
        Map<String, int[]> monthlyStats = new TreeMap<>(); // 存储每个月的总数和 releaseStatus = 1 的次数

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            while (rs.next()) {
                LocalDateTime buildTime = rs.getObject("buildTime", LocalDateTime.class);
                int releaseStatus = rs.getInt("releaseStatus");

                // 获取自然月周期，例如 "2024-01"
                String month = getMonthPeriod(buildTime);

                // 初始化统计数据
                monthlyStats.putIfAbsent(month, new int[]{0, 0});

                // 更新统计
                monthlyStats.get(month)[0]++; // 总记录数加1
                if (releaseStatus == 1) {
                    monthlyStats.get(month)[1]++; // releaseStatus = 1 的次数加1
                }
            }

            // 遍历统计数据，计算百分比并填充返回值
            for (Map.Entry<String, int[]> entry : monthlyStats.entrySet()) {
                String month = entry.getKey();
                int[] stats = entry.getValue();
                int totalCount = stats[0];
                int releaseStatusCount = stats[1];
                double percentage = totalCount > 0
                        ? new BigDecimal(releaseStatusCount * 100.0 / totalCount)
                        .setScale(2, RoundingMode.HALF_UP)
                        .doubleValue()
                        : 0.0;

                months.add(month);
                totalCounts.add(totalCount);
                releaseStatusCounts.add(releaseStatusCount);
                percentages.add(percentage);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 构造返回数据
        timePeriods.put("month", months);
        Map<String, Object> response = new HashMap<>();
        response.put("timePeriods", timePeriods);
        response.put("totalCounts", totalCounts);
        response.put("releaseStatusCounts", releaseStatusCounts);
        response.put("percentages", percentages);

        return response;
    }

    public Map<String, Object> getC2ReleaseSucRateByWeeks() {
        // 返回数据的结构
        Map<String, List<String>> timePeriods = new HashMap<>();
        List<String> weeks = new ArrayList<>();
        List<Integer> totalCounts = new ArrayList<>();
        List<Integer> releaseStatusCounts = new ArrayList<>();
        List<Double> percentages = new ArrayList<>();

        String sql = "SELECT `buildTime`, COALESCE(`releaseStatus`, 0) AS `releaseStatus` FROM `c2_version_info`;";
        System.out.println("Executing SQL: " + sql);

        // 使用 TreeMap 确保按时间顺序存储
        Map<String, int[]> weeklyStats = new TreeMap<>(); // 存储每周的总数和 releaseStatus = 1 的次数

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            while (rs.next()) {
                LocalDateTime buildTime = rs.getObject("buildTime", LocalDateTime.class);
                int releaseStatus = rs.getInt("releaseStatus");

                // 获取自然周周期，例如 "2024-W01"
                String week = getWeekPeriod(buildTime);

                // 初始化统计数据
                weeklyStats.putIfAbsent(week, new int[]{0, 0});

                // 更新统计
                weeklyStats.get(week)[0]++; // 总记录数加1
                if (releaseStatus == 1) {
                    weeklyStats.get(week)[1]++; // releaseStatus = 1 的次数加1
                }
            }

            // 遍历统计数据，计算百分比并填充返回值
            for (Map.Entry<String, int[]> entry : weeklyStats.entrySet()) {
                String week = entry.getKey();
                int[] stats = entry.getValue();
                int totalCount = stats[0];
                int releaseStatusCount = stats[1];
                double percentage = totalCount > 0
                        ? new BigDecimal(releaseStatusCount * 100.0 / totalCount)
                        .setScale(2, RoundingMode.HALF_UP)
                        .doubleValue()
                        : 0.0;

                weeks.add(week);
                totalCounts.add(totalCount);
                releaseStatusCounts.add(releaseStatusCount);
                percentages.add(percentage);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 构造返回数据
        timePeriods.put("week", weeks);
        Map<String, Object> response = new HashMap<>();
        response.put("timePeriods", timePeriods);
        response.put("totalCounts", totalCounts);
        response.put("releaseStatusCounts", releaseStatusCounts);
        response.put("percentages", percentages);

        return response;
    }

    public Map<String, Object> getC2ReleaseSucRateByYears() {
        // 返回数据的结构
        Map<String, List<String>> timePeriods = new HashMap<>();
        List<String> years = new ArrayList<>();
        List<Integer> totalCounts = new ArrayList<>();
        List<Integer> releaseStatusCounts = new ArrayList<>();
        List<Double> percentages = new ArrayList<>();

        String sql = "SELECT `buildTime`, COALESCE(`releaseStatus`, 0) AS `releaseStatus` FROM `c2_version_info`;";
        System.out.println("Executing SQL: " + sql);

        // 使用 TreeMap 确保按时间顺序存储
        Map<String, int[]> yearlyStats = new TreeMap<>(); // 存储每年的总数和 releaseStatus = 1 的次数

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            while (rs.next()) {
                LocalDateTime buildTime = rs.getObject("buildTime", LocalDateTime.class);
                int releaseStatus = rs.getInt("releaseStatus");

                // 获取自然年，例如 "2024"
                String year = String.valueOf(buildTime.getYear());

                // 初始化统计数据
                yearlyStats.putIfAbsent(year, new int[]{0, 0});

                // 更新统计
                yearlyStats.get(year)[0]++; // 总记录数加1
                if (releaseStatus == 1) {
                    yearlyStats.get(year)[1]++; // releaseStatus = 1 的次数加1
                }
            }

            // 遍历统计数据，计算百分比并填充返回值
            for (Map.Entry<String, int[]> entry : yearlyStats.entrySet()) {
                String year = entry.getKey();
                int[] stats = entry.getValue();
                int totalCount = stats[0];
                int releaseStatusCount = stats[1];
                double percentage = totalCount > 0
                        ? new BigDecimal(releaseStatusCount * 100.0 / totalCount)
                        .setScale(2, RoundingMode.HALF_UP)
                        .doubleValue()
                        : 0.0;

                years.add(year);
                totalCounts.add(totalCount);
                releaseStatusCounts.add(releaseStatusCount);
                percentages.add(percentage);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 构造返回数据
        timePeriods.put("year", years);
        Map<String, Object> response = new HashMap<>();
        response.put("timePeriods", timePeriods);
        response.put("totalCounts", totalCounts);
        response.put("releaseStatusCounts", releaseStatusCounts);
        response.put("percentages", percentages);

        return response;
    }

    /**
     * 根据日期获取自然月周期，例如 "2024-01"
     */
    private String getMonthPeriod(LocalDateTime buildTime) {
        return buildTime.getYear() + "-" + String.format("%02d", buildTime.getMonthValue());
    }

    private String getWeekPeriod(LocalDateTime releaseTime) {
        // 将 LocalDateTime 转换为 LocalDate，只保留日期部分
        LocalDate date = releaseTime.toLocalDate();

        // 获取年份和该日期的自然周
        int year = date.getYear();
        int week = releaseTime.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);

        // 获取该周的开始日期（周一）
        LocalDate startOfWeek = date.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, week)
                .with(IsoFields.WEEK_BASED_YEAR, year)
                .with(java.time.temporal.TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));

        // 获取该周的结束日期（周日）
        LocalDate endOfWeek = startOfWeek.plusDays(6);

        // 使用 "MM/dd" 格式化日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd");
        return startOfWeek.format(formatter) + "-" + endOfWeek.format(formatter);
    }
}